﻿#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace Hont.BlazingNodePackage
{
    public class SubscribeMessageNode : Node
    {
        public enum ModeEnum { OverlapMode, LazyMode }
        public ModeEnum Mode;
        public string MessageName;
        Coroutine mCoroutine;

        public override string Name { get { return "Subscribe Message"; } }
        public override string Category { get { return "Message"; } }
        public override Vector2 Size { get { return new Vector2(120, 40); } }


        public SubscribeMessageNode()
        {
        }

        protected override void Init()
        {
            base.Init();

            mInPortList.Clear();

            mCoroutine = null;
        }

        public override void OnAwake(Document document)
        {
            var standardContext = Context as StandardContext;

            standardContext.MessageManager.Subscribe(MessageName, ReceivedMessageCBMethod);
        }

        public override void OnDestroy()
        {
            var standardContext = Context as StandardContext;

            standardContext.MessageManager.Unsubscribe(MessageName, ReceivedMessageCBMethod);
        }

        void ReceivedMessageCBMethod()
        {
            var standardContext = Context as StandardContext;

            switch (Mode)
            {
                case ModeEnum.OverlapMode:
                    if (mCoroutine != null)
                        standardContext.MonoBehaviour.StopCoroutine(mCoroutine);
                    break;
                case ModeEnum.LazyMode:
                    if (mCoroutine != null) return;
                    break;
            }

            mCoroutine = standardContext.MonoBehaviour
                .StartCoroutine(BlazingNodeHelper.ToFixedCoroutine(ExecuteMessage()));

            standardContext.SubCoroutinesHashSet.Add(mCoroutine);
        }

        IEnumerator ExecuteMessage()
        {
            yield return ExecutePort(mOutPortList[0]);

            var standardContext = Context as StandardContext;
            standardContext.SubCoroutinesHashSet.Remove(mCoroutine);
            mCoroutine = null;
        }

        public override IEnumerator Execute(Port port)
        {
            yield return true;
        }

        public override void OnDrawAttributesGUI(out bool updateUI)
        {
            updateUI = false;
#if UNITY_EDITOR
            EditorGUI.BeginChangeCheck();
            Mode = (ModeEnum)EditorGUILayout.EnumPopup("Mode ", Mode);
            MessageName = EditorGUILayout.TextField("Message ", MessageName);
            if (EditorGUI.EndChangeCheck())
            {
                updateUI = true;
            }
#endif
        }
    }
}
